package cn.yujiago.springboot.service.impl;

import cn.yujiago.springboot.mapper.NewsMapper;
import cn.yujiago.springboot.pojo.LayuiTableResult;
import cn.yujiago.springboot.entity.News;
import cn.yujiago.springboot.service.NewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@CacheConfig(cacheNames = "news", cacheManager = "redisCacheManager")
@Service
public class NewsServiceImpl implements NewsService {

    @Resource
    private NewsMapper newsMapper;
    @Resource
    private PageHelper pageHelper;

    @Override
    @Cacheable(key = "'getNewsByCondition'+#page+#rows+#newsName", unless = "#result==null")
    public LayuiTableResult<News> getNewsByCondition(Integer page, Integer rows, String newsName) {

        // 1、设置分页信息，包括当前页数和每页显示的总计数
        pageHelper.startPage(page, rows);

        List<News> newsList = newsMapper.selectNewsByCondition(newsName);

        // 3、获取分页查询后的数据
        PageInfo<News> pageInfo = new PageInfo<>(newsList);
        // 4、创建返回结果对象
        LayuiTableResult<News> result = new LayuiTableResult<>();
        if(newsList != null){
            result.setCode(0);
            result.setMsg("查询成功！");
            // 设置获取到的总记录数total
            result.setCount(pageInfo.getTotal());
            result.setData(newsList);
            return result;
        }else{
            result.setCode(1);
            result.setMsg("查询失败！");
            return result;
        }
    }

}
